import { getUserList } from '@/apis/accessManagement/user'
import { resetPassword } from '@/apis/accessManagement/user'
import { blockUser } from '@/apis/accessManagement/user'
import { forceLogout } from '@/apis/accessManagement/user'
import ExcelTable from '@/components/exportExcel'
import { ActionType, ProFormInstance } from '@ant-design/pro-components'
import {Button, Drawer, Modal, Form, Input, Flex, Tree, message} from 'antd'
import {useRef, useState,useEffect} from 'react'
import {useNavigate} from 'react-router-dom'
import md5 from 'js-md5'
import { storeGlobalUser } from '@/store/globalUser'

const UserList: React.FC = () => {
    useRef<ActionType>()
    useRef<ProFormInstance>()
    const { TextArea } = Input
    const navigate = useNavigate()
    const actionRef = useRef();
    const [tableItem, setTableItem] = useState()
    const [passwordParam, setPasswordParam] = useState('')
    const [forbiddenParam, setForbiddenParam] = useState('')
    const [form] = Form.useForm()
    const [restPwd, setResetPwdDrawer] = useState(false)
    const [forbiddenUser, setForbiddenUser] = useState(false)
    const [addUserAuth, setAddUserAuth] = useState(false)
    const [editUserAuth, setEditUserAuth] = useState(false)
    const [resetPwdAuth, setResetPwdAuth] = useState(false)
    const [forbiddenAuth, setForbiddenAuth] = useState(false)
    const [messageApi, contextHolder] = message.useMessage();

    function showResetPwdDrawer(item: any) {
        // setTableItem(item)
        setPasswordParam(item.userID)
        setResetPwdDrawer(true)
    }

    function showForbiddenDrawer(item: any) {
        console.log(item.userID)
        setPasswordParam(item.userID)
        setForbiddenUser(true)
    }

    const subNewPwd = async ()=> {
        const reset = form.getFieldValue('reset');
        const cfmSet = form.getFieldValue('cfmSet');
        if (reset !== cfmSet) {
            message.error('两次密码输入不一致');
            return;
        }
        try {
            await updatePassword(passwordParam); 
        } catch (error) {
            console.log(error)
        }
    }

    // 提交新密码
    const updatePassword = async (params:any) => {
        try {
            const response = await resetPassword({
                newPassword: md5(form.getFieldValue('reset')),
                userID: passwordParam,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('密码修改成功');
                    navigate('/user/userManage/userList?current=1&pageSize=10')
                } else {
                    message.error(`修改失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
            form.resetFields()
            setResetPwdDrawer(false)
        } catch (error) {
            console.error('Error:', error);
        }
    };

    // 禁用用户
    const subForbidden = async (params:any) => {
        try {
            const response = await blockUser({
                reason: form.getFieldValue('forbidden'),
                userID: passwordParam,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('禁用成功');
                    actionRef.current?.reloadAndRest()
                    // window.location.reload()
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
            form.resetFields()
            setForbiddenUser(false)
        } catch (error) {
            console.error('Error:', error);
        }
    };

    // 强制下线
    const forceLogoutUser = async (params:any) => {
        try {
            const response = await forceLogout({
                platformID: 0,
                userID: params.userID,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    message.success('强制下线成功');
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    function onCloseDrawer() {
        form.resetFields()
        setResetPwdDrawer(false)
    }

    function onCloseForbiddenDrawer() {
        form.resetFields()
        setForbiddenUser(false)
    }

    useEffect(() => {
        const processAuthData = (authData: any[]) => {
            // 递归
            const traverse = (nodes: any[]) => {
                for (const node of nodes) {
                    if (node.name === '用户' && node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                    // 检查子节点的 name
                    if (node.name === '新增用户') {
                        setAddUserAuth(true)
                    }
                    if (node.name === '编辑用户') {
                        setEditUserAuth(true)
                    }
                    if (node.name === '重置密码') {
                        setResetPwdAuth(true)
                    }
                    if (node.name === '禁用') {
                        setForbiddenAuth(true)
                    }
                    // 如果两个权限都已经找到，提前结束递归
                    if (addUserAuth && editUserAuth && resetPwdAuth && forbiddenAuth) {
                        return;
                    }
                    // 如果当前节点有子节点，递归处理子节点
                    if (node.children && node.children.length > 0) {
                        traverse(node.children);
                    }
                }
            };
            traverse(authData);
            return { addUserAuth, editUserAuth,resetPwdAuth,forbiddenAuth };
        };
        const checkRouters = setInterval(() => {
            const authData = window.routers?.routes?.[1]?.children || [];
            if (authData.length > 0) {
                clearInterval(checkRouters); // 停止检查
                processAuthData(authData); // 执行逻辑
            }
        }, 200);
        return () => clearInterval(checkRouters); // 清理定时器
    },[])

    return (
        <>
            {contextHolder}
            <ExcelTable
                actionRef={actionRef}
                requestFn={ params => {
                    const { pageNum,pageSize,nickname, ...newParams } = params; // 处理所需参数名
                    const data = getUserList({
                        ...newParams,
                        pagination: {pageNumber:pageNum,showNumber:pageSize}, 
                        keyword: params.nickname || params.userID,
                        normal:1
                    })
                    return data
                }}
                rowSelection={false}
                toolBarRenderFn={() => [
                    addUserAuth && (
                        <Button key="add" onClick={() => {
                            navigate('/user/userManage/addUser?state=1')
                        }}>添加</Button>
                    )
                ]}
                columns={[
                    {
                        title: '序号',
                        valueType: 'index',
                        hideInSearch: true
                    },
                    {
                        title: '用户',
                        dataIndex: 'nickname',
                    },
                    {
                        title: '用户ID',
                        dataIndex: 'userID',
                        hideInSearch: true
                    },
                    {
                        title: '性别',
                        dataIndex: 'gender',
                        hideInSearch: true,
                        valueType: 'select',
                        valueEnum: {
                            1: '男',
                            2: '女',
                        }
                    },
                    // {
                    //     title: '用户状态',
                    //     dataIndex: 'userStatus',
                    //     hideInSearch: true,
                    //     valueType: 'select',
                    //     valueEnum: {
                    //         2: '全部',
                    //         1: '正常',
                    //         0: '禁用',
                    //     }
                    // },
                    {
                        title: '注册时间',
                        dataIndex: 'createTime',
                        hideInSearch: true,
                        valueType: 'dateTime'
                    },
                    {
                        title: '最近登录时间',
                        dataIndex: 'lastLoginTime',
                        hideInSearch: true,
                        valueType: 'dateTime'
                    },
                    // {
                    //     title: '操作人',
                    //     dataIndex: 'operator',
                    //     hideInSearch: true,
                    // },
                    {
                        title: '是否允许添加好友',
                        hideInSearch: true,
                        dataIndex: 'allowAddFriend',
                        render: (_, record) => record.allowAddFriend === 1?'允许':'不允许',
                    },
                    {
                        title: '操作',
                        key: 'option',
                        valueType: 'option',
                        render: (_, record) => [
                            editUserAuth && (<a key="update" onClick={() => {navigate(`/user/userManage/setUser?state=2&userID=${record.userID}`)}}>修改信息</a>),
                            resetPwdAuth && (<a key="resetPwd" onClick={() => showResetPwdDrawer(record)}>重置密码</a>),
                            forbiddenAuth && (<a key="disabled" onClick={() => showForbiddenDrawer(record)}>禁用</a>),
                            // <a key="disabled" onClick={() => {
                            //     const forbiddenText = record.userStatus === 1 ? '禁言' : '解除禁言'
                            //     Modal.warning({
                            //         title: '提示',
                            //         content: `确定${forbiddenText}该用户吗?`,
                            //         okText: '确定',
                            //         okCancel: true,
                            //         onOk() {
                            //             console.log('Confirmed:onOk ')
                            //         }
                            //     })
                            // }}>{record.userStatus === 1?'禁言':'解除禁言'}</a>,
                            // <a key="delete" onClick={() => {
                            //     Modal.warning({
                            //         title: '提示',
                            //         content: '确定强制下线该用户吗?',
                            //         okText: '确定',
                            //         okCancel: true,
                            //         onOk() {
                            //             forceLogoutUser(record)
                            //         }
                            //     })
                            // }}>强制下线</a>
                        ]
                    }
                ]}/>
            <Drawer title="重置密码" onClose={onCloseDrawer} open={restPwd}>
                <Form form={form} onFinish={subNewPwd}>
                    <Form.Item label="重置密码" name="reset" rules={[{required: true, message: '请输入新密码'},{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                        <Input placeholder="请输入新密码" maxLength={50}/>
                    </Form.Item>
                    <Form.Item label="确认密码" name="cfmSet" rules={[{required: true, message: '请再次输入新密码'},{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                        <Input placeholder="请再次输入新密码" maxLength={50}/>
                    </Form.Item>
                    <Form.Item>
                        <Flex justify='center' align='center'>
                            <Button type="primary" htmlType="submit">提交</Button>
                            <Button style={{marginLeft: 10}} onClick={onCloseDrawer}>返回</Button>
                        </Flex>
                    </Form.Item>
                </Form>
            </Drawer>
            <Drawer title="确定禁用此用户吗？" onClose={onCloseForbiddenDrawer} open={forbiddenUser}>
                <p>禁用后此用户将只出现在封禁列表</p>
                <Form form={form} onFinish={subForbidden}>
                    <Form.Item label="禁用原因" name="forbidden" rules={[{required: true, message: '请输入禁用原因'},{ max: 100, message: '最多输入100个字符' }]}>
                        <TextArea rows={4} maxLength={100} placeholder="请输入禁用原因，最多不超过200字。" />
                    </Form.Item>
                    <Form.Item>
                        <Flex justify='center' align='center'>
                            <Button type="primary" htmlType="submit">提交</Button>
                            <Button style={{marginLeft: 10}} onClick={onCloseForbiddenDrawer}>返回</Button>
                        </Flex>
                    </Form.Item>
                </Form>
            </Drawer>
        </>
    )
}

export default UserList
